package com.zhangjie.cmn.service.lmpl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhangjie.cmn.listener.DictListener;
import com.zhangjie.cmn.mapper.DictMapper;
import com.zhangjie.cmn.service.DictService;
import com.zhangjie.model.cmn.Dict;
import com.zhangjie.vo.cmn.DictEeVo;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService{
    @Autowired
    private DictMapper dictMapper;
    //根据数据id查询子数据列表
    @Override
    //开启缓存    缓存的名字     会按照配置类里配置的这个规格写入
//    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    public List<Dict> findChlidData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        List<Dict> dictList = baseMapper.selectList(wrapper);   //核心
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);    //查询他还有没有子数据
            dict.setHasChildren(isChild);
        }
        return dictList;
    }

    //导出数据字典接口
    @Override
    //把这个规则下单缓存都清空
//    @CacheEvict(value = "dict",allEntries = true)
    public void exportDictData(HttpServletResponse response){
        //设置 content 类型
//        response.setContentType("application/vnd.ms-excel");
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        String fileName = "dict";       //设置名字
        response.setHeader("Content-disposition", "attachment;filename="+ fileName + ".xlsx");
        //查询数据库
        List<Dict> dictList = baseMapper.selectList(null);
        //Dict -- DictEeVo
        List<DictEeVo> dictVoList = new ArrayList<>();
        for(Dict dict:dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            BeanUtils.copyProperties(dict,dictEeVo);
            dictVoList.add(dictEeVo);
        }
        //调用方法进行写操作
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典")
                    .doWrite(dictVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override//导入数据字典
    public void importDictData(MultipartFile file){
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(dictMapper));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override//根据条件查询 名字
    public String getDictName(String dictCode, String value) {
        //如果dictCode是null，直接根据value查询
        if (StringUtils.isEmpty(dictCode)){
            //直接根据value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value",value);
            Dict dict = baseMapper.selectOne(wrapper);
            if (dict!=null){
                return dict.getName();
            }
            return null;
        }else {//不为空,根据两个条件来查询
            //根据dictCode查询Dict对象，得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);//这里去查询整行记录
            Long parent_id = codeDict.getId();//拿到当前行的id当做要查询的类的父类id    高啊  ---注意看这里
            //根据parent_id和value进行查询
            Dict findDict = baseMapper.selectOne(new QueryWrapper<Dict>()
                    .eq("parent_id", parent_id)//查询一个父类的数据
                    .eq("value", value));   //查询同一value的值
            return findDict.getName();
        }
    }

    @Override//根据dictCode获取下级节点
    public List<Dict> findByDictCode(String dictCode) {
        Dict dict = this.getDictByDictCode(dictCode);  //查询整行记录
        //根据id获取子节点
        List<Dict> chlidData = this.findChlidData(dict.getId());
        return chlidData;
    }

    //根据dictCoded去查询整行记录
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code",dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    //导入数据字典
//    @Override
//    @CacheEvict(value = "dict", allEntries=true)
//    public void importDictData(MultipartFile file) {
//        try {
//            EasyExcel.read(file.getInputStream(), DictEeVo.class,new DictListener(baseMapper)).sheet().doRead();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }

//    //根据dictcode和value查询
////    @Override
//    public String getDictName(String dictCode, String value) {
//        //如果dictCode为空，直接根据value查询
//        if(StringUtils.isEmpty(dictCode)) {
//            //直接根据value查询
//            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
//            wrapper.eq("value",value);
//            Dict dict = baseMapper.selectOne(wrapper);
//            return dict.getName();
//        } else {//如果dictCode不为空，根据dictCode和value查询
//            //根据dictcode查询dict对象，得到dict的id值
//            Dict codeDict = this.getDictByDictCode(dictCode);
//            Long parent_id = codeDict.getId();
//            //根据parent_id和value进行查询
//            Dict finalDict = baseMapper.selectOne(new QueryWrapper<Dict>()
//                    .eq("parent_id", parent_id)
//                    .eq("value", value));
//            return finalDict.getName();
//        }
//    }

//    //根据dictCode获取下级节点
////    @Override
//    public List<Dict> findByDictCode(String dictCode) {
//        //根据dictcode获取对应id
//        Dict dict = this.getDictByDictCode(dictCode);
//        //根据id获取子节点
//        List<Dict> chlidData = this.findChlidData(dict.getId());
//        return chlidData;
//    }


    //判断id下面是否有子节点
    public boolean isChildren(Long id){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        return count>0;
    }
}
